<template>
    <div id="app">
        <el-card>
            <template #header>
                <div class="header">AI 对话界面</div>
            </template>
            <div class="chat-container" ref="chatContainerRef">
                <div class="message" v-for="(msg, index) in messages" :key="index">
                    <img
                            v-if="msg.sender === 'ai'"
                            src="https://dummyimage.com/30x30/00ff00/ffffff&text=AI"
                            alt="AI 头像"
                            class="avatar"
                    >
                    <span :class="msg.sender === 'user' ? 'user-message' : 'ai-message'">
            {{ msg.content }}
          </span>
                    <img
                            v-if="msg.sender === 'user'"
                            src="https://dummyimage.com/30x30/0000ff/ffffff&text=U"
                            alt="用户头像"
                            class="avatar"
                    >
                </div>
            </div>
            <el-form @submit.prevent="sendMessage">
                <el-input v-model="inputMessage" placeholder="请输入你的消息" ref="inputRef"></el-input>
                <el-button type="primary" @click="sendMessage">发送</el-button>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';

const inputRef = ref(null);
const chatContainerRef = ref(null);
const inputMessage = ref('');
const messages = ref([
    { sender: 'ai', content: '你好！有什么可以帮助你的？' }
]);

const sendMessage = () => {
    if (inputMessage.value.trim() === '') return;

    messages.value.push({ sender: 'user', content: inputMessage.value });
    inputMessage.value = '';
    // 模拟 AI 回复
    setTimeout(async () => {
        messages.value.push({ sender: 'ai', content: '这是 AI 的回复。' });
        await nextTick();
        scrollToBottom();
    }, 1000);
    inputRef.value.focus();
    scrollToBottom();
};

const scrollToBottom = () => {
    if (chatContainerRef.value) {
        chatContainerRef.value.scrollTop = chatContainerRef.value.scrollHeight;
    }
};

watch(messages, async () => {
    await nextTick();
    scrollToBottom();
});
</script>

<style scoped>
.header {
    font-size: 18px;
    font-weight: bold;
}

.chat-container {
    height: 300px;
    overflow-y: auto;
    border: 1px solid #e4e7ed;
    padding: 10px;
    margin-bottom: 10px;
}

.message {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
}

.user-message {
    background-color: #e4f7ff;
    padding: 8px;
    border-radius: 4px;
    margin-left: auto;
}

.ai-message {
    background-color: #f0f9eb;
    padding: 8px;
    border-radius: 4px;
    margin-right: auto;
}

.avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin: 0 8px;
}
</style>